import { Injectable } from '@angular/core';
import { Http,} from "@angular/http";
import { ApiService } from "../../environments/environment";
import { TreeNode } from "primeng/components/common/treenode";
@Injectable()
export class OrganizationService {
  departments : TreeNode[] ;
  constructor(private http: Http,private api: ApiService) {
    this.GetAre();
    this.GetData = this.api.Info.GetDepartmentList().then((result:any) => {
      let itemcol = this.itemcol;
      let items: { id: number, name: string, path: string }[] = result;
      items.push({ id: 0, name: '创业空间', path: '0' });
      items.sort((a,b)=>{
        return a.name.localeCompare(b.name);
      });
      items.forEach((item) => {
        itemcol[item.path] = item;
      });
      return items;
    });
  }

  itemcol:any={};

  GetData:Promise<{ id: number, name: string, path: string }[]>;

  GetFilter(filter?: string) {
    if (filter && filter.trim()) filter=filter.trim();
    let allitem = this.itemcol;
    return this.GetData.then(items=>{
      let thisitem: any = {};
      let filterdata: { id: number, name: string, path: string }[];
      if (!filter || filter.trim() == '') return [...items];

      filterdata = items.filter(item => item.name.indexOf(filter) != -1);//查找匹配到的节点
      filterdata.forEach(item => { thisitem[item.path] = true; });
      let lastitems = [...filterdata];//最终生成树所需要数据
      filterdata.forEach(item => {//查找匹配到的节点父节点
        let lastindex = item.path.lastIndexOf('.');
        while (lastindex != -1) {
          let path = item.path.substr(0, lastindex);
          if (!thisitem[path]) {
            thisitem[path] = true;
            if (allitem[path])
              lastitems.push(allitem[path]);
          }
          lastindex = path.lastIndexOf('.');
        }
      });
      filterdata.forEach(item => {//查找匹配到的节点子节点
        let children = items.filter(i => {
          if (thisitem[i.path]) return false;
          if (i.path.indexOf(item.path) == -1) return false;
          thisitem[i.path] = true;
          return true;
        });
        lastitems.push(...children);
      });
      return lastitems;
    })
  }

  GetTreeData(filter?: string) {
   return  this.GetFilter(filter).then(treedata => {
      // let treedata = this.GetFilter(filter);
      let allnode: any = {};
      let rootnodes: TreeNode[] = [];

      let expanded = false;
      if (filter && filter.trim()) expanded = true;

      let treenodes = treedata.map(item => {
        let node = <TreeNode>{
          label: item.name,
          expandedIcon: "fa-folder-open",
          collapsedIcon: "fa-folder",
          data: item,
          expanded: expanded
        }
        allnode[item.path] = node;

        if (item.path.indexOf('.') == -1) {
          node.expanded = true;
          rootnodes.push(node);
        }
        return node;
      });

      treenodes.forEach(item => {
        let lastindex = item.data.path.lastIndexOf('.');
        if (lastindex != -1) {
          var parentpath = item.data.path.substr(0, lastindex);
          let parentnode: TreeNode = allnode[parentpath];
          if(parentnode){
          if (!parentnode.children) parentnode.children = [];
          parentnode.children.push(item);
          }
        }
      });

      return rootnodes;
    })
  }

  GetPerson(id:number,name?:string){
    // let option: RequestOptionsArgs = { params: {  } };
    // if(name) option.params['name'] = name;
    // return this.http.get('/api/Info/GetEmployeeList/'+id,option).toPromise().then(res=>{
    //   let jsondata = res.json();
    //   if(jsondata &&jsondata.result){
    //     return <{id:number,name:string}[]>jsondata.data;
    //   }
    //   return <{id:number,name:string}[]>[];
    // });
  }

  areas:{id:number,name:string}[];

  GetAre(){
    return this.api.GetEntryAreaList().then(res=>{
      this.areas = res.map(item=>{return {id:item.id,name:item.name }});
      // let jsondata = res.json();
      // if(jsondata &&jsondata.result){
      //   this.areas = jsondata.data.map(item=>{return {id:item.id,name:item.name }});
      // }
    });
  }

  GetTree(): TreeNode[] {
    return [
      {
          "label": "Documents",
          "data": "Documents Folder",
          "expandedIcon": "fa-folder-open",
          "collapsedIcon": "fa-folder",
          "children": [{
                  "label": "Work",
                  "data": "Work Folder",
                  "expandedIcon": "fa-folder-open",
                  "collapsedIcon": "fa-folder",
                  "children": [{"label": "Expenses.doc", "icon": "fa-file-word-o", "data": "Expenses Document"}, {"label": "Resume.doc", "icon": "fa-file-word-o", "data": "Resume Document"}]
              },
              {
                  "label": "Home",
                  "data": "Home Folder",
                  "expandedIcon": "fa-folder-open",
                  "collapsedIcon": "fa-folder",
                  "children": [{"label": "Invoices.txt", "icon": "fa-file-word-o", "data": "Invoices for this month"}]
              }]
      },
      {
          "label": "Pictures",
          "data": "Pictures Folder",
          "expandedIcon": "fa-folder-open",
          "collapsedIcon": "fa-folder",
          "children": [
              {"label": "barcelona.jpg", "icon": "fa-file-image-o", "data": "Barcelona Photo"},
              {"label": "logo.jpg", "icon": "fa-file-image-o", "data": "PrimeFaces Logo"},
              {"label": "primeui.png", "icon": "fa-file-image-o", "data": "PrimeUI Logo"}]
      },
      {
          "label": "Movies",
          "data": "Movies Folder",
          "expandedIcon": "fa-folder-open",
          "collapsedIcon": "fa-folder",
          "children": [{
                  "label": "Al Pacino",
                  "data": "Pacino Movies",
                  "children": [{"label": "Scarface", "icon": "fa-file-video-o", "data": "Scarface Movie"}, {"label": "Serpico", "icon": "fa-file-video-o", "data": "Serpico Movie"}]
              },
              {
                  "label": "Robert De Niro",
                  "data": "De Niro Movies",
                  "children": [{"label": "Goodfellas", "icon": "fa-file-video-o", "data": "Goodfellas Movie"}, {"label": "Untouchables", "icon": "fa-file-video-o", "data": "Untouchables Movie"}]
              }]
      }
  ];
  }
}
